package frame;

import Base.FileOperation;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONWriter;
import common.User;
import function.GetFriendList;
import function.GetMessage;
import function.LogIn;
import function.SearchUser;
import global.Const;
import global.PublciVariable;
import other.DButton;
import other.HeadImage;
import panel.common.BackGround;
import panel.home.Userinfo;
import thread.Sleep;
import windows.LoadingDialog;
import windows.MessageDialog;

import javax.swing.*;
import java.awt.*;

public class Home extends JFrame implements Runnable {
    public static MessageDialog messageDialog = new MessageDialog();
    public static LoadingDialog loadingDialog = new LoadingDialog();

    // 组件
    private UserPane userPane = new UserPane();
    private FriendList friendList = new FriendList();
    private BottomBar bottomBar = new BottomBar();
    private User user = new User();
    private Thread thread;
    private boolean isAlive = true;

//    public Home() {
//        init();
//    }

    private void init() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(Const.FRAME_WIDTH, Const.FRAME_HEIGHT - 5);
        setLocationRelativeTo(null);
        setTitle(Const.TITLE);
        setResizable(false);
        setLayout(null);


        // 加载
        BackGround backGround = new BackGround("src/main/resources/image/home/firefly.jpg");// 背景
        // 添加组件
        add(loadingDialog);
        add(messageDialog);
        add(userPane);
        add(friendList);
        add(bottomBar);
        add(backGround);

        // 加载
        loadUser(); // 登录
        userPane.init(user);
        friendList.init();
        bottomBar.init();
        repaint();
    }

    // 用户信息
    public class UserPane extends JPanel {
        public void init(User user) {
            setLayout(null);
            setBounds(0, 0, 540, 200);
            setBackground(new Color(0, 0, 0, 100));
            // 头像
            HeadImage headImage = new HeadImage(PublciVariable.username);
            headImage.setBounds(0, 0, 200);
            // 用户名
            JLabel username = new JLabel(PublciVariable.username);
            username.setBackground(new Color(0, 0, 0, 200));
            username.setFont(new Font("微软雅黑", Font.PLAIN, 50));
            username.setForeground(Color.white);
            username.setBounds(200, 0, 340, 70);
            username.setHorizontalAlignment(SwingConstants.CENTER);
            username.setVerticalAlignment(SwingConstants.CENTER);
            // 个性签名
            JTextArea signature = new JTextArea();
            signature.setText(user.sign);
            signature.setBackground(new Color(0, 0, 0, 200));
            signature.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            signature.setForeground(Color.gray);
            signature.setBounds(200, 70, 340, 130);
            signature.setLineWrap(true);
            signature.setWrapStyleWord(true);
            signature.setEditable(false);
            signature.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

            // 添加组件
            add(headImage);
            add(username);
            add(signature);
//            repaint();
        }
    }

    // 好友列表
    public class FriendList extends JPanel {
        private int friendAmount = 0;
        public int height = 130;
        private static final int maxFriendAmount = 5;

        public void init() {
            setLayout(null);
            setBounds(0, 200, 540, 650);
            setBackground(new Color(0, 0, 0, 100));
            height = getHeight() / maxFriendAmount;

            // 获取好友列表
            JSONObject friends = GetFriendList.get(PublciVariable.username);
            try {
                if (friends.getInteger("code") == 0) {
                    JSONArray friendList = friends.getJSONArray("data");
                    if (!friendList.isEmpty())
                        addFriends(friendList);
                    return;
                } else {
                    System.out.print("获取好友列表失败\n" + friends.toString(JSONWriter.Feature.PrettyFormat));
                }
            } catch (Exception e) {
                System.out.print("获取好友列表失败\n" + friends.toString(JSONWriter.Feature.PrettyFormat));
                // 打印错误
                e.printStackTrace();
            }

            add(new Nofriend());
        }

        public void addFriends(JSONArray friends) {
            for (int i = 0; i < friends.size(); i++) {
                JSONObject friend = SearchUser.get(friends.getJSONObject(i).getString("username"));
                User user = new User();
                user.username = friend.getString("username");
                user.sign = friend.getString("sign");
                user.allowStrangerChat = friend.getBoolean("allowStrangerChat");
                add(new Userinfo(user, friendAmount));
                friendAmount++;
            }
        }

        public class Nofriend extends JLabel {
            public Nofriend() {
                super("暂无好友");
                if (getParent() != null)
                    setBounds(0, 0, getParent().getWidth(), getParent().getHeight());
                else
                    setBounds(0, 0, 540, 650);
                setSize(540, 650);
                setFont(new Font("微软雅黑", Font.PLAIN, 50));
                setForeground(Color.white);
                setHorizontalAlignment(SwingConstants.CENTER);
                setVerticalAlignment(SwingConstants.CENTER);
            }
        }
    }

    // 底部栏
    public class BottomBar extends JPanel {
        public void init() {
            setLayout(null);
            setBounds(0, 850, 540, 110);
            setBackground(new Color(0, 0, 0, 100));
//            setBackground(Color.green);
            // 退出登录按钮
            DButton logOut = new DButton("退出登录");
            logOut.setSize(160, 64);
            logOut.setLocation(40, getHeight() / 2 - logOut.getHeight() / 2);
            logOut.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            logOut.setForeground(Color.white);
            logOut.setBackground(Color.red);
            logOut.addActionListener(e -> logOut());
            // 添加好友按钮
            DButton addFriend = new DButton("添加好友");
            addFriend.setSize(160, 64);
            addFriend.setLocation(340, getHeight() / 2 - addFriend.getHeight() / 2);
            addFriend.setFont(new Font("微软雅黑", Font.PLAIN, 20));
            addFriend.setForeground(Color.white);
            addFriend.setBackground(Color.blue);
            addFriend.addActionListener(e -> new FindUser());

            // 添加组件
            add(logOut);
            add(addFriend);
            repaint();
        }
    }

    public void open() {
        init();
        setVisible(true);
        repaint();
        thread = new Thread(this);
        thread.start();
    }

    public void close() {
        isAlive = false;
        setVisible(false);
    }

    public void loadUser() {
        JSONObject user = FileOperation.readJson("src/main/resources/data/user/log");
        String username = user.getString("username");
        String password = user.getString("password");

        while (true) {
            loadingDialog.open();
            JSONObject receive = LogIn.get(username, password);
            loadingDialog.close();
            if (receive.getInteger("code") == 0) {
                System.out.print("登录成功");
                PublciVariable.username = user.getString("username");
                PublciVariable.password = user.getString("password");
                setUser(SearchUser.get(username));
                return;
            } else if (receive.getInteger("code") == 404) {
                messageDialog.open("登录失败", "请检查网络连接后重试");
            } else {
                messageDialog.open("登录已失效，请重新登录");
                messageDialog.button.addActionListener(e -> logOut());
            }
        }
    }

    public void setUser(JSONObject userJson) {
        user = new User(userJson);
    }

    public void logOut() {
        JSONObject user = FileOperation.readJson("src/main/resources/data/user/log");
        user.put("password", null);
        FileOperation.writeJson("src/main/resources/data/user/log", user);
        System.exit(0);
    }

    // 监听服务器消息
    @Override
    public void run() {
        while (isAlive) {
            JSONObject receive = GetMessage.get(PublciVariable.username);
            // 有消息
            if (receive.getInteger("code") == 0) {
                JSONArray data = receive.getJSONArray("data");
                String username = PublciVariable.username;
                String sender = data.getJSONObject(0).getString("sender");
                // 读取本地数据
                JSONArray local = PublciVariable.messageList.getJSONArray(sender);
                // 合并数据
                if (local != null)
                    data.addAll(local);
                // 保存数据
                PublciVariable.messageList.put(sender, data);
//                System.out.print("messageList" + PublciVariable.messageList.toString(JSONWriter.Feature.PrettyFormat) + "\n");
                // 判断是否打开聊天框
                if (PublciVariable.chatList.getBoolean(sender) == null) {
                    JSONObject senderJson = SearchUser.get(sender);
                    if (senderJson.getInteger("code") == 0) {
                        User user = new User(senderJson);
                        new Chat(user);
                    } else messageDialog.open("未找到用户");
                }
            }

            Sleep.sleep(100);
        }
    }
}
